/*
 * Copyright (C) 2011 by ayoung <ayoung.p@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.peaceb.ruletherain;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Utility class
 */
public class Util {
    
    /**
     * Extract file extension from full path
     *  XXX XXX XXX not used, need to re-write XXX XXX XXX
     *  
     * @param path
     * @return
     */
    public static String extractFileExtension(String path) {
        if (path == null) {
            return null;
        }
        
        int dotIndex = path.lastIndexOf('.');
        if (dotIndex < 0) {
            return null;
        }
        
        return path.substring(dotIndex + 1);
    }
    
    /**
     * Extract file base name from full path.
     * /aaa/bbb/ccc.ext -> ccc
     * 
     * @param path
     * @return
     */
    public static String extractFileBaseName(String path) {
        if (path == null) {
            return null;
        }
        int len   = path.length();
        if (len == 0) {
            Trace.v("length is 0");
            return null;
        }
        
        int start = path.lastIndexOf('/');
        int end   = path.lastIndexOf('.');

        start = (start < 0) ? 0 : (start < len) ? start + 1 : 0;
        end   = (end < 0) ? len - 1 : end;
            
        return path.substring(start, end);
    }
    
    /**
     * Show toast in long time
     * 
     * @param context
     * @param msg
     */
    public static void showToast(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
    }
    
    /**
     * Show toast in long time
     * 
     * @param context
     * @param strResId
     */
    public static void showToast(Context context, int strResId) {
        Toast.makeText(context, strResId, Toast.LENGTH_LONG).show();
    }
    
    /**
     * Check network status
     * 
     * @param context
     * @return
     */
    public static boolean isNetworkAvail(Context context) {
        ConnectivityManager cm = 
            (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        
        for (NetworkInfo info : cm.getAllNetworkInfo()) {
            if (info.isConnected()) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Hide soft keyboard
     * 
     * @param context
     * @param edit
     */
    public static void hideSoftkeyboard(Context context, EditText edit) {
        InputMethodManager imm = 
            (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        
        imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
    }
    
    /**
     * Get device model name
     * 
     * @return
     */
    public static String getModelName() {
        return Build.MODEL;
    }
    
    /**
     * Get android version
     * 
     * @return
     */
    public static String getAndroidVersion() {
        return Build.VERSION.RELEASE;
    }
    
    /**
     * Get network operator name
     * 
     * @param context
     * @return
     */
    public static String getNetworkOperatorName(Context context) {
        String networkName = null;
        
        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm != null) {
            networkName = tm.getNetworkOperatorName();
        }
        
        return networkName;
    }
    
    /**
     * Get external files directory.
     */
    public static String getExternalFilesDir(Context context, String packageName) {
        if (Integer.parseInt(Build.VERSION.SDK) < 8 /* Build.VERSION_CODES.FROYO */) {
            Trace.i("Not supported: getExternalFilesDir (" + Build.VERSION.SDK + ")");
            return null;
        }
        
        Method method = null;
        File   path   = null;
        
        try {
            method = Context.class.getMethod("getExternalFilesDir", new Class[] { String.class });
        } catch (SecurityException e) {
            Trace.e(e.toString());
            return null;
        } catch (NoSuchMethodException e) {
            Trace.e(e.toString());
            return null;
        }
        
        if (method != null) {
            try {
                path = (File)method.invoke(context, new Object[] { null });
            } catch (IllegalArgumentException e) {
                Trace.e(e.toString());
                return null;
            } catch (IllegalAccessException e) {
                Trace.e(e.toString());
                return null;
            } catch (InvocationTargetException e) {
                Trace.e(e.toString());
                return null;
            }
        }
        
        String filesDir = null;
        if (path != null && path.getAbsolutePath() != null) {
            filesDir = path.getAbsolutePath().replace(context.getPackageName(), packageName);
        }
        return filesDir;
    }
}
